package com.admin.commen;

import com.fegin.bean.admin.AdminUser;
import com.util.Respons.ResponseUtil;
import com.util.exception.CommonException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authz.HostUnauthorizedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author 张子艺
 * @packge com.controller.config
 * @data 2019-01-08 15:51
 * @project Currency
 */
@Configuration
public class BaseController {

    public AdminUser getUser() {
        return (AdminUser) SecurityUtils.getSubject().getPrincipal();
    }

    /***
     * 判断一个请求是否为AJAX请求,是则返回true
     * @param request
     * @return
     */
    public   boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        //如果requestType能拿到值，并且值为 XMLHttpRequest ,表示客户端的请求为异步请求，那自然是ajax请求了，反之如果为null,则是普通的请求
        if (requestType == null) {
            return false;
        }
        return true;

    }

    /**
     * 程序异常
     * 因为有切面日志的原因如果控制层报错 则会打印两次日志  一次是请求的切点 一次是 本异常类的切点
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> serverException(Exception e) {

        //  logger.error(e.getStackTrace());
        if (e instanceof ExpiredCredentialsException) {
            return ResponseUtil.getLoginOutTimeMap();
        }
        if (e instanceof HostUnauthorizedException) {
            return ResponseUtil.NoAuth();
        }
        if (e instanceof UnauthorizedException) {
            return ResponseUtil.NoAuth();
        }
        if (e instanceof CommonException) {
            return ResponseUtil.RequestException(e.getMessage());
        }
        e.printStackTrace(System.out);
        return ResponseUtil.getExceptionMap();
    }
}
